package com.autobet.services.thread;

import com.autobet.dao.CommonDao;
import com.autobet.model.support.AutoResult;
import com.autobet.model.table.AutoHis;
import com.autobet.model.table.ResultHis;
import com.autobet.services.BetService;
import com.autobet.services.EnvConfigService;
import com.autobet.services.ResultService;
import com.autobet.utils.BetUtils;
import com.autobet.utils.IdGenerator;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by yangd on 2017-08-27.
 */
public class QueryResultThread extends Thread {
    private static final Logger log = LoggerFactory.getLogger(QueryResultThread.class);
    private String name;
    private String betType;
    private long sleepTime = (long)(1000 * Integer.parseInt(EnvConfigService.getQueryResultIntervalTime()));
    private static long lstatus = 0L;
    private Map<String, BigDecimal> buydateIdcacheMap = new HashMap();

    public QueryResultThread(String name) {
        this.name = name;
    }

    /**
     * 获取开奖结果
     */
    public void run() {
        CommonDao commonDao = (CommonDao)EnvConfigService.getApplicationContext().getBean(CommonDao.class);
        ResultService resultService = (ResultService)EnvConfigService.getApplicationContext().getBean(ResultService.class);
        BetService betService = (BetService)EnvConfigService.getApplicationContext().getBean(BetService.class);

        while(true) {
            ++lstatus;

            try {
                Thread.sleep(this.sleepTime);
            } catch (InterruptedException var17) {
                log.error("线程休眠错误！更新开奖结果失败！", var17);
                betService.stopBetForException("线程休眠错误！更新开奖结果失败！请暂停系统重新开始");
            }

            if(!EnvConfigService.getTaskStatus().equals("RUNING")) {
                log.info("系统执行状态不正确，退出查询结果任务");
                resultService.addInfo("系统执行状态不正确，退出查询结果任务");
                return;
            }

            if( !"".equals(EnvConfigService.searchDate)){
                log.info("历史结果数据不查询最新数据！");
                return;
            }

            try {
                AutoResult autoResult = resultService.getCurrentResultRetry(6);
                ResultHis rh = commonDao.queryResultHisByBuydateId(autoResult.getBuydateId());
                if(rh == null || rh.getBuydateId() == null) {
                    ResultHis resultHis = new ResultHis();
                    resultHis.setDataId(IdGenerator.getSLId());
                    resultHis.setBuydateId(autoResult.getBuydateId());
                    resultHis.setInsertDate(new Date());
                    resultHis.setFirstFlag("n");
                    resultHis.setResultDate(BetUtils.getCurrDateYYYYMMDD());
                    resultHis.setR1(autoResult.getBuyResultArray()[0]);
                    resultHis.setR2(autoResult.getBuyResultArray()[1]);
                    resultHis.setR3(autoResult.getBuyResultArray()[2]);
                    resultHis.setR4(autoResult.getBuyResultArray()[3]);
                    resultHis.setR5(autoResult.getBuyResultArray()[4]);
                    resultHis.setR6(autoResult.getBuyResultArray()[5]);
                    resultHis.setR7(autoResult.getBuyResultArray()[6]);
                    resultHis.setR8(autoResult.getBuyResultArray()[7]);
                    resultHis.setR9(autoResult.getBuyResultArray()[8]);
                    resultHis.setR10(autoResult.getBuyResultArray()[9]);
                    resultHis.setFirstArea(autoResult.getBuyResultArray()[0]+","+autoResult.getBuyResultArray()[1]+","+autoResult.getBuyResultArray()[2]+","+
                            autoResult.getBuyResultArray()[3]+","+autoResult.getBuyResultArray()[4]+",");
                    resultHis.setSecondArea(autoResult.getBuyResultArray()[5]+","+autoResult.getBuyResultArray()[6]+","+autoResult.getBuyResultArray()[7]+","+
                            autoResult.getBuyResultArray()[8]+","+autoResult.getBuyResultArray()[9]);
                    List<ResultHis> list = new ArrayList();
                    list.add(resultHis);
                    commonDao.saveOrUpdateResultHis(list);
                }

                /*计算结果*/
                rh = commonDao.queryResultHisByBuydateId(autoResult.getBuydateId());
                if( (rh.getFirstSelect() == null || rh.getFirstSelect().isEmpty() && (rh.getSecondSelect() == null || rh.getSecondSelect().isEmpty()))){
                    if(resultService.buildSelect(rh)){
                        resultService.addInfo("第"+autoResult.getBuydateId()+"期获取结果计算成功！");
                        log.info("第"+autoResult.getBuydateId()+"期获取结果计算成功！");
                    }else{
                        betService.stopBetForException("更新开奖结果失败！");
                    }
                }else{
                    resultService.addInfo("第"+autoResult.getBuydateId()+"期已经计算！");
                    log.info("第"+autoResult.getBuydateId()+"期已经计算！");
                }

//                String buydateId = autoResult.getBuydateId();
//                List<AutoHis> betList = commonDao.queryAutoHisByBuydateIdAndBetType(buydateId, this.betType);
//                if(betList != null && betList.size() != 0) {
//                    AutoHis oneAutoHis = (AutoHis)betList.get(0);
//                    if(!"00".equals(oneAutoHis.getBuyResult().trim())) {
//                        log.info("{}期已经更新过结果，无须更新数据库", oneAutoHis.getBuydateId());
//                        resultService.addInfo("" + oneAutoHis.getBuydateId() + "期已经更新过结果，无须更新数据库，继续...");
////                        log.info("盈亏统计开始！");
////                        resultService.sumTakeMomey();
////                        log.info("盈亏统计结束！");
//                    } else {
//                        List<AutoHis> resultAutohisList = new ArrayList();
//
//                        AutoHis autoHis;
//                        for(Iterator var10 = betList.iterator(); var10.hasNext(); resultAutohisList.add(autoHis)) {
//                            autoHis = (AutoHis)var10.next();
//                            autoHis.setCurrBuyresult(autoResult.getBuyResult());
//                            String buyNum = autoHis.getBuyNum();
//                            String betWhat = autoHis.getBuyWhat();
//                            String betResult = autoResult.getBuyResultArray()[Integer.parseInt(buyNum) - 1];
//
//
//                            double realmoneytake;
//                            double realmoneytakeReadly;
//                            if("dx".equals(autoHis.getBuyType())) {
//                                if(BetUtils.isBetWin("dx", betWhat, betResult)) {
//                                    autoHis.setBuyResult("01");
//                                    autoHis.setBuyMoneytake(autoHis.getBuyAmount());
//                                    realmoneytake = (double)autoHis.getBuyAmount().intValue() * (Double.parseDouble(EnvConfigService.getMoneytakeRate()) - 1.0D);
//                                    autoHis.setBuyRMoneytake(new BigDecimal(realmoneytake));
//
//                                    autoHis.setBuyMoneyTakeReadly(autoHis.getBuyAmountReadly());
//                                    realmoneytakeReadly = (double)autoHis.getBuyAmountReadly().intValue() * (Double.parseDouble(EnvConfigService.getMoneytakeRate()) - 1.0D);
//                                    autoHis.setBuyRMoneyTakeReadly(new BigDecimal(realmoneytakeReadly));
//                                } else {
//                                    autoHis.setBuyResult("02");
//                                    autoHis.setBuyMoneytake(new BigDecimal("-" + autoHis.getBuyAmount().doubleValue()));
//                                    autoHis.setBuyRMoneytake(new BigDecimal("-" + autoHis.getBuyAmount().doubleValue()));
//
//                                    autoHis.setBuyMoneyTakeReadly(new BigDecimal("-" + autoHis.getBuyAmountReadly().doubleValue()));
//                                    autoHis.setBuyRMoneyTakeReadly(new BigDecimal("-" + autoHis.getBuyAmountReadly().doubleValue()));
//                                }
//                            } else {
//                                if(!"ds".equals(autoHis.getBuyType())) {
//                                    log.error("玩法匹配不上！");
//                                    throw new Exception("玩法匹配不上！");
//                                }
//
//                                if(BetUtils.isBetWin("ds", betWhat, betResult)) {
//                                    autoHis.setBuyResult("01");
//                                    autoHis.setBuyMoneytake(autoHis.getBuyAmount());
//                                    realmoneytake = (double)autoHis.getBuyAmount().intValue() * (Double.parseDouble(EnvConfigService.getMoneytakeRate()) - 1.0D);
//                                    autoHis.setBuyRMoneytake(new BigDecimal(realmoneytake));
//
//                                    autoHis.setBuyMoneyTakeReadly(autoHis.getBuyAmount());
//                                    realmoneytakeReadly = (double)autoHis.getBuyAmountReadly().intValue() * (Double.parseDouble(EnvConfigService.getMoneytakeRate()) - 1.0D);
//                                    autoHis.setBuyRMoneyTakeReadly(new BigDecimal(realmoneytakeReadly));
//
//                                } else {
//                                    autoHis.setBuyResult("02");
//                                    autoHis.setBuyMoneytake(new BigDecimal("-" + autoHis.getBuyAmount().doubleValue()));
//                                    autoHis.setBuyRMoneytake(new BigDecimal("-" + autoHis.getBuyAmount().doubleValue()));
//
//                                    autoHis.setBuyMoneyTakeReadly(new BigDecimal("-" + autoHis.getBuyAmountReadly().doubleValue()));
//                                    autoHis.setBuyRMoneyTakeReadly(new BigDecimal("-" + autoHis.getBuyAmountReadly().doubleValue()));
//                                }
//                            }
//                        }
//
//                        commonDao.updateAutoHisByBuydateId(resultAutohisList);
//                        log.info("结果数据更新数据库完毕！");
//                        resultService.addInfo("开奖结果数据更新数据库完毕！继续查询开奖结果...");
//                        log.info("盈亏统计开始！");
//                        resultService.sumTakeMomey();
//                        log.info("盈亏统计结束！");
//                    }
//                } else {
//                    log.info("本次查询期数{}，数据库无记录!", buydateId);
//                    resultService.addInfo("本次查询期数" + buydateId + "数据库无记录!继续...");
//                    BigDecimal querytimes = (BigDecimal)this.buydateIdcacheMap.get(buydateId);
//                    if(querytimes == null) {
//                        this.buydateIdcacheMap.put(buydateId, new BigDecimal(0));
//                    } else if(querytimes.intValue() > 2) {
//                        log.info("查询了3次系统仍然没有{}期下注记录", buydateId);
//                        betService.stopBetForException("查询了3次系统仍然没有" + buydateId + "期下注记录,系统可能已经丢失数据，请重新启动补齐数据...");
//                    } else {
//                        this.buydateIdcacheMap.put(buydateId, new BigDecimal(querytimes.intValue() + 1));
//                    }
//                }
            } catch (Exception var18) {
                log.error("更新开奖结果失败！", var18);
                betService.stopBetForException("更新开奖结果失败！");
                log.info("线程结束.....");
                return;
            }
        }
    }

    public static long getLstatus() {
        return lstatus;
    }

}